const { sys_menu, sys_form, sys_form_field, op } = require("../../middleware/baseModel");
const autoFile = require("../service/autoFile");
const funTool = require("../../tool/funTool");

module.exports = {
  "GET /sys_menu/index": async (ctx, next) => {
    const menuRows = await sys_menu.findAll({
      order: [["sort", "ASC"]],
    });

    let newMenuRows = menuRows.map((row) => {
      let newRow = row.toJSON();
      let nodeIds = funTool.getParantNode(newRow, menuRows);
      newRow.parent_node_ids = nodeIds.reverse();
      return newRow;
    });

    return ctx.success(newMenuRows);
  },

  "POST /sys_menu/add": async (ctx, next) => {
    let row = ctx.getBody();
    const res = await sys_menu.create(row);
    let menu_id = res.id;

    let model_id = row.model_id;
    if (menu_id && model_id) {
      await autoFile.createForm(menu_id, model_id);
      await autoFile.autoFrontEndApi(menu_id);
      await autoFile.autoFrontEndVue(menu_id);
    }

    return ctx.success(res);
  },

  "POST /sys_menu/generate": async (ctx, next) => {
    let row = ctx.getBody();

    let { id: menu_id, model_id } = row;
    if (menu_id && model_id) {
      await autoFile.createForm(menu_id, model_id);
      await autoFile.autoFrontEndApi(menu_id);
      await autoFile.autoFrontEndVue(menu_id);
    }

    return ctx.success();
  },

  "POST /sys_menu/build": async (ctx, next) => {
    let cmd = `npm run build`;
    let msg = await funTool.execCmd(cmd).catch((e) => {
      return ctx.fail(e.message);
    });
    return ctx.success(msg);
  },

  "POST /sys_menu/edit": async (ctx, next) => {
    let row = ctx.getBody();
    let id = ctx.get("id");

    const resList = await sys_menu.update(row, {
      where: {
        id: id,
      },
    });


    let { id: menu_id, model_id } = row;
    if (menu_id && model_id) {
      await autoFile.createForm(menu_id, model_id);
      await autoFile.autoFrontEndApi(menu_id);
      await autoFile.autoFrontEndVue(menu_id);
    }


    return ctx.success(resList);
  },

  "POST /sys_menu/del": async (ctx, next) => {
    let id = ctx.get("id");
    await autoFile.destroyVueFile(id);
    const res = await sys_menu.destroy({ where: { id: id } });
    return ctx.success(res);
  },
};
